// src/utils/cacheManager.js
// SMT 双缓存系统管理工具

/**
 * SMT 双缓存系统键名定义
 * 
 * 本地缓存① - 基础订单数据缓存 (SMT_BASE_CACHE)
 * 存储: lineId, mounterId, operatorId, orderBranchNo, orderNo, partList
 * 
 * 本地缓存② - 扫描记录缓存 (SMT_SCAN_CACHE) 
 * 存储: 具体的扫描记录数据(smtSide, lotNo, partId, rollMngNo, rollNo, scanTimestamp, smtProcess等)
 */
export const CACHE_KEYS = {
  SMT_BASE_CACHE: 'smtBaseCache',        // 本地缓存① - 基础订单和部品信息
  SMT_SCAN_CACHE: 'smtScanCache'         // 本地缓存② - 扫描记录数据
};

// ==================== 本地缓存① - 基础订单数据管理 ====================

/**
 * 设置基础订单数据缓存 (本地缓存①)
 * @param {Object} baseData 基础订单数据
 * @param {string} baseData.lineId - 线体ID
 * @param {string} baseData.mounterId - 实装机ID  
 * @param {string} baseData.operatorId - 作业员ID
 * @param {string} baseData.orderBranchNo - 订单分支号
 * @param {string} baseData.orderNo - 订单号
 * @param {Array} baseData.partList - 部品列表 [{rollNo, partId}, ...]
 * @returns {boolean} 是否设置成功
 */
export function setBaseCacheData(baseData) {
  try {
    const dataToStore = {
      type: 'base_cache',
      timestamp: Date.now(),
      data: {
        lineId: baseData.lineId || '',
        mounterId: baseData.mounterId || '',
        operatorId: baseData.operatorId || '',
        orderBranchNo: baseData.orderBranchNo || '01',
        orderNo: baseData.orderNo || '',
        smtSide: baseData.smtSide || '', // 添加smtSide字段
        partList: baseData.partList || []
      }
    };
    
    uni.setStorageSync(CACHE_KEYS.SMT_BASE_CACHE, dataToStore);
    console.log('✅ 本地缓存① 基础订单数据已保存:', dataToStore.data);
    return true;
  } catch (error) {
    console.error('❌ 保存基础订单数据失败:', error);
    return false;
  }
}

/**
 * 获取基础订单数据缓存 (本地缓存①)
 * @returns {Object|null} 基础订单数据
 */
export function getBaseCacheData() {
  try {
    const cachedData = uni.getStorageSync(CACHE_KEYS.SMT_BASE_CACHE);
    if (!cachedData || cachedData.type !== 'base_cache') {
      console.warn('⚠️ 本地缓存① 基础订单数据不存在');
      return null;
    }
    
    console.log('✅ 获取本地缓存① 基础订单数据:', cachedData.data);
    return cachedData.data;
  } catch (error) {
    console.error('❌ 获取基础订单数据失败:', error);
    return null;
  }
}

/**
 * 更新基础订单数据缓存的特定字段 (本地缓存①)
 * @param {Object} updates 要更新的字段对象
 * @returns {boolean} 是否更新成功
 */
export function updateBaseCacheData(updates) {
  try {
    const currentData = getBaseCacheData();
    if (!currentData) {
      console.error('❌ 没有现有的基础订单数据可以更新');
      return false;
    }

    // 合并更新
    const updatedData = { ...currentData, ...updates };
    console.log('🔄 更新本地缓存① 数据:', updates);
    
    return setBaseCacheData(updatedData);
  } catch (error) {
    console.error('❌ 更新基础订单数据失败:', error);
    return false;
  }
}

// ==================== 本地缓存② - 扫描记录数据管理 ====================

/**
 * 设置扫描缓存数据 (本地缓存②)
 * @param {Object} scanData 扫描数据
 * @param {Object} scanData.baseInfo - 基础信息
 * @param {Array} scanData.successRecords - 成功记录数组
 * @param {Array} scanData.failureRecords - 失败记录数组
 * @returns {boolean} 是否设置成功
 */
export function setScanCacheData(scanData) {
  try {
    const dataToStore = {
      type: 'scan_cache',
      timestamp: Date.now(),
      data: {
        baseInfo: scanData.baseInfo || {},
        successRecords: scanData.successRecords || [],
        failureRecords: scanData.failureRecords || [],
        statistics: {
          uniquePartCount: 0,
          lastScanTime: new Date().toISOString()
        }
      }
    };
    
    // 计算统计信息
    if (scanData.successRecords && scanData.successRecords.length > 0) {
      const uniqueParts = new Set(scanData.successRecords.map(r => r.partId));
      dataToStore.data.statistics.uniquePartCount = uniqueParts.size;
    }
    
    uni.setStorageSync(CACHE_KEYS.SMT_SCAN_CACHE, dataToStore);
    console.log('✅ 本地缓存② 扫描记录数据已保存:', {
      successCount: dataToStore.data.successRecords.length,
      failureCount: dataToStore.data.failureRecords.length,
      uniqueParts: dataToStore.data.statistics.uniquePartCount
    });
    return true;
  } catch (error) {
    console.error('❌ 保存扫描记录数据失败:', error);
    return false;
  }
}

/**
 * 获取扫描缓存数据 (本地缓存②)
 * @returns {Object} 扫描记录数据
 */
export function getScanCacheData() {
  try {
    const cachedData = uni.getStorageSync(CACHE_KEYS.SMT_SCAN_CACHE);
    if (!cachedData || cachedData.type !== 'scan_cache') {
      console.warn('⚠️ 本地缓存② 扫描记录数据不存在，返回默认结构');
      return getDefaultScanCacheData();
    }
    
    console.log('✅ 获取本地缓存② 扫描记录数据:', {
      successCount: cachedData.data.successRecords?.length || 0,
      failureCount: cachedData.data.failureRecords?.length || 0,
      uniqueParts: cachedData.data.statistics?.uniquePartCount || 0
    });
    return cachedData.data;
  } catch (error) {
    console.error('❌ 获取扫描记录数据失败:', error);
    return getDefaultScanCacheData();
  }
}

/**
 * 获取默认的扫描缓存数据结构
 * @returns {Object} 默认扫描缓存数据
 */
export function getDefaultScanCacheData() {
  const baseData = getBaseCacheData();
  return {
    baseInfo: {
      lineId: baseData?.lineId || '',
      mounterId: baseData?.mounterId || '',
      operatorId: baseData?.operatorId || '',
      orderBranchNo: baseData?.orderBranchNo || '01',
      orderNo: baseData?.orderNo || '',
      smtSide: baseData?.smtSide || '', // 从基础缓存获取smtSide
      lotNo: '',
      partId: '',
      rollMngNo: '',
      rollNo: '',
      scanTimestamp: '',
      smtProcess: ''
    },
    successRecords: [],
    failureRecords: [],
    statistics: {
      uniquePartCount: 0,
      lastScanTime: ''
    }
  };
}

/**
 * 添加成功扫描记录到本地缓存②
 * @param {Object} scanRecord 扫描记录
 * @param {string} scanRecord.partId - 部品ID
 * @param {string} scanRecord.lotNo - 批次号
 * @param {number} scanRecord.rollNo - Roll号
 * @param {string} scanRecord.rollMngNo - Roll管理号
 * @param {string} scanRecord.smtSide - 实装面
 * @returns {boolean} 是否添加成功
 */
export function addSuccessScanRecord(scanRecord) {
  try {
    const scanCacheData = getScanCacheData();
    const baseData = getBaseCacheData();
    
    if (!baseData) {
      console.error('❌ 没有基础缓存数据，无法添加扫描记录');
      return false;
    }
    
    // 构建完整的成功记录
    const fullRecord = {
      lineId: baseData.lineId,
      mounterId: baseData.mounterId,
      operatorId: baseData.operatorId,
      orderBranchNo: baseData.orderBranchNo,
      orderNo: baseData.orderNo,
      partId: scanRecord.partId,
      lotNo: scanRecord.lotNo,
      rollNo: scanRecord.rollNo,
      rollMngNo: scanRecord.rollMngNo || '',
      smtSide: scanRecord.smtSide || '1',
      scanTimestamp: new Date().toISOString(),
      smtProcess: '98' // 成功状态
    };
    
    scanCacheData.successRecords.push(fullRecord);
    
    // 更新统计信息
    const uniqueParts = new Set(scanCacheData.successRecords.map(r => r.partId));
    scanCacheData.statistics.uniquePartCount = uniqueParts.size;
    scanCacheData.statistics.lastScanTime = fullRecord.scanTimestamp;
    
    const success = setScanCacheData(scanCacheData);
    if (success) {
      console.log('✅ 成功记录已添加:', {
        partId: scanRecord.partId,
        lotNo: scanRecord.lotNo,
        totalSuccess: scanCacheData.successRecords.length,
        uniqueParts: uniqueParts.size
      });
    }
    return success;
  } catch (error) {
    console.error('❌ 添加成功扫描记录失败:', error);
    return false;
  }
}

/**
 * 添加失败扫描记录到本地缓存②
 * @param {Object} failureRecord 失败记录
 * @param {string} failureRecord.smtContent - 错误内容描述
 * @param {string} failureRecord.partId - 部品ID (可选)
 * @returns {boolean} 是否添加成功
 */
export function addFailureScanRecord(failureRecord) {
  try {
    const scanCacheData = getScanCacheData();
    const baseData = getBaseCacheData();
    
    if (!baseData) {
      console.error('❌ 没有基础缓存数据，无法添加失败记录');
      return false;
    }
    
    // 构建完整的失败记录
    const fullRecord = {
      lineId: baseData.lineId,
      mounterId: baseData.mounterId,
      operatorId: baseData.operatorId,
      orderBranchNo: baseData.orderBranchNo,
      orderNo: baseData.orderNo,
      smtContent: failureRecord.smtContent,
      smtProcess: '99', // 失败状态
      scanTimestamp: new Date().toISOString()
    };
    
    // 如果有部品ID，添加到记录中
    if (failureRecord.partId) {
      fullRecord.partId = failureRecord.partId;
    }
    
    scanCacheData.failureRecords.push(fullRecord);
    scanCacheData.statistics.lastScanTime = fullRecord.scanTimestamp;
    
    const success = setScanCacheData(scanCacheData);
    if (success) {
      console.log('✅ 失败记录已添加:', {
        smtContent: failureRecord.smtContent,
        totalFailure: scanCacheData.failureRecords.length
      });
    }
    return success;
  } catch (error) {
    console.error('❌ 添加失败扫描记录失败:', error);
    return false;
  }
}

/**
 * 获取唯一部品数量
 * @returns {number} 唯一部品数量
 */
export function getUniquePartCount() {
  try {
    const scanCacheData = getScanCacheData();
    const uniqueParts = new Set(scanCacheData.successRecords.map(r => r.partId));
    return uniqueParts.size;
  } catch (error) {
    console.error('❌ 获取唯一部品数量失败:', error);
    return 0;
  }
}

/**
 * 检查是否为重复的部品+批次组合
 * @param {string} partId 部品ID
 * @param {string} lotNo 批次号
 * @returns {boolean} 是否重复
 */
export function checkDuplicateLot(partId, lotNo) {
  try {
    const scanCacheData = getScanCacheData();
    return scanCacheData.successRecords.some(record => 
      record.partId === partId && record.lotNo === lotNo
    );
  } catch (error) {
    console.error('❌ 检查重复批次失败:', error);
    return false;
  }
}

/**
 * 清除扫描缓存数据 (本地缓存②)
 * @returns {boolean} 是否清除成功
 */
export function clearScanCacheData() {
  try {
    uni.removeStorageSync(CACHE_KEYS.SMT_SCAN_CACHE);
    console.log('✅ 本地缓存② 扫描记录数据已清除');
    return true;
  } catch (error) {
    console.error('❌ 清除扫描记录数据失败:', error);
    return false;
  }
}

/**
 * 清除基础缓存数据 (本地缓存①)
 * @returns {boolean} 是否清除成功
 */
export function clearBaseCacheData() {
  try {
    uni.removeStorageSync(CACHE_KEYS.SMT_BASE_CACHE);
    console.log('✅ 本地缓存① 基础订单数据已清除');
    return true;
  } catch (error) {
    console.error('❌ 清除基础订单数据失败:', error);
    return false;
  }
}

/**
 * 清除所有双缓存数据
 * @returns {Object} 清除结果
 */
export function clearAllCacheData() {
  const result = {
    baseCacheCleared: clearBaseCacheData(),
    scanCacheCleared: clearScanCacheData()
  };
  
  console.log('🧹 双缓存系统清除结果:', result);
  return result;
}

/**
 * 获取当前缓存状态信息
 * @returns {Object} 缓存状态
 */
export function getCacheStatus() {
  try {
    const storage = uni.getStorageInfoSync();
    const baseData = getBaseCacheData();
    const scanData = getScanCacheData();
    
    return {
      totalKeys: storage.keys.length,
      currentSize: storage.currentSize,
      limitSize: storage.limitSize,
      hasBaseData: !!baseData,
      hasEmptyDefaultScanData: !scanData.successRecords.length && !scanData.failureRecords.length,
      baseDataPartCount: baseData?.partList?.length || 0,
      scanSuccessCount: scanData.successRecords?.length || 0,
      scanFailureCount: scanData.failureRecords?.length || 0,
      uniquePartCount: scanData.statistics?.uniquePartCount || 0,
      allKeys: storage.keys
    };
  } catch (error) {
    console.error('❌ 获取缓存状态失败:', error);
    return null;
  }
}

/**
 * 准备提交到后端的数据格式
 * @returns {Object|null} 提交数据
 */
export function prepareSubmissionData() {
  try {
    const baseData = getBaseCacheData();
    const scanData = getScanCacheData();
    
    if (!baseData) {
      console.error('❌ 没有基础缓存数据，无法准备提交');
      return null;
    }
    
    return {
      orderInfo: {
        orderNo: baseData.orderNo,
        orderBranchNo: baseData.orderBranchNo,
        mounterId: baseData.mounterId,
        smtSide: scanData.baseInfo.smtSide || baseData?.smtSide || '1', // 优先从扫描缓存获取，其次从基础缓存获取，最后默认为1
        operatorId: baseData.operatorId,
        lineId: baseData.lineId
      },
      successRecords: scanData.successRecords,
      failureRecords: scanData.failureRecords
    };
  } catch (error) {
    console.error('❌ 准备提交数据失败:', error);
    return null;
  }
}